﻿using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using System.Net;

namespace GMusicBox.Core
{
    public static class LyricsDownloader
    {
        public static string DownloadLyrics(Song s)
        {
            SongStreaming ss = new SongStreaming(s.Id);
            ss.GetSongStreamingData();
            return DownloadLyrics(s, ss);
        }

        public static string DownloadLyrics(Song mbi, SongStreaming mdi)
        {
            Settings s = new Settings(Settings.SettingSavePath + "\\Config\\Configs\\Config.xml");
            string path = s["SaveLyric"];
            if (path.StartsWith("\\")) path = path.Insert(0, Settings.SettingSavePath);
            Helper.CreateDirectory(Path.GetDirectoryName(path));

            if (mdi != null)
            {
                path += mbi.Id + Path.GetExtension(mdi.LyricsUrl);
                if (!File.Exists(path))
                {
                    path += ".lrc";
                    if (!File.Exists(path))
                    {
                        path = path.Substring(0, path.Length - 4);
                        try
                        {
                            WebClient wc = new WebClient();
                            wc.DownloadFile(new Uri(mdi.LyricsUrl), path);
                            wc.Dispose();
                        }
                        catch
                        {
                            Directory.CreateDirectory(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + "\\GMusicBox");
                            Program.CreatHiddenProfile(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + "\\GMusicBox" + "\\temp.lrc", Encoding.UTF8.GetBytes("[00:00.01]抱歉，无法获取歌词内容或不存在此歌曲的歌词\r\n[99:99.90]"));
                            return Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + "\\GMusicBox" + "\\temp.lrc";
                        }
                    }
                }
            }
            else
            {
                if (File.Exists(path + mbi.Id + ".lrc")) return path + mbi.Id + ".lrc";
                else if (File.Exists(path + mbi.Id + ".txt")) return path + mbi.Id + ".txt";
                else
                {
                    Directory.CreateDirectory(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + "\\GMusicBox");
                    Program.CreatHiddenProfile(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + "\\GMusicBox" + "\\temp.lrc", Encoding.UTF8.GetBytes("[00:00.01]抱歉，无法获取歌词内容或不存在此歌曲的歌词\r\n[99:99.90]"));
                    return Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + "\\GMusicBox" + "\\temp.lrc";
                }
            }
            return path;
        }
    }
}
